請使用Artisan 命令:make:middleware
php artisan make:middleware CheckWord
今天來做可以過濾不好字眼產品名稱的中間件
將要處理的邏輯放在hadle函數中
public function handle(Request $request, Closure $next)
{
$checkwords = [ // 隨便舉個範例
'cool',
'wow'
];
$parameters = $request->all();
foreach($parameters as $key => $value){
if ($key == "name"){
foreach($checkwords as $checkword){
if (strpos($checkword, $value) !== false){
return response('請重新輸入', 400);
}
}
}
}
return $next($request);
}
如果您希望在對您的應用程序的每個 HTTP 請求期間運行中間件,只需在app/Http/Kernel.php
中列出你的$middleware類,只需將其附加到此列表並為其分配您選擇的鍵。
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'check.word' => \App\Http\Middleware\CheckWord::class,
];
Route::group(['middleware' => ['check.word']], function () {
Route::resource('/product', 'productController');
});
成功!!!!